package com.nullpointer.playerinfo.bungee;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import com.magic0610.MagicYaml.MagicYaml;
import com.magic0610.MagicYaml.YamlConfig;
import com.magic0610.MagicYaml.BukkitConfiguration.file.YamlConfiguration;
import com.nullpointer.playerinfo.common.Base;
import com.nullpointer.playerinfo.common.objects.Correspond;
import com.nullpointer.playerinfo.common.objects.Player;

import net.md_5.bungee.api.plugin.Plugin;
import net.md_5.bungee.api.scheduler.ScheduledTask;

public class PlayerInfoBungee extends Plugin {
    public static Plugin plugin;

    public static YamlConfiguration config;
    public static YamlConfiguration level;
    public static Mysql mysql;
    public static Map<UUID, ScheduledTask> playerTimerMap = new HashMap<>();

    // 通信
    public static Correspond corresponder;

    @Override
    public void onEnable() {
        plugin = this;

        getLogger().info("加载配置文件...");
        MagicYaml magicYaml = new MagicYaml(getDataFolder(), "bungee", false);
        YamlConfig bungeeCofigYC = magicYaml.saveResource("config.yml", false);
        YamlConfig levelCofigYC = magicYaml.saveResource("level.yml", false);
        config = bungeeCofigYC.getConfig();
        level = levelCofigYC.getConfig();

        if (bungeeCofigYC.needUpdate()) {
            bungeeCofigYC.update(false);
        }
        if (levelCofigYC.needUpdate()) {
            levelCofigYC.update(false);
        }

        Base.hotUpdate = config.getBoolean("hot_update");
        if (isDatabaseNotConfigured()) {
            getLogger().severe("数据库还未配置，请在config.yml中配置");
            return;
        }

        getLogger().info("初始化数据库..."); //初始化数据库
        mysql = new Mysql(
            config.getString("mysql.host"), 
            config.getInt("mysql.port"), 
            config.getString("mysql.database"), 
            config.getString("mysql.username"), 
            config.getString("mysql.password")
        );
        mysql.connect();

        getLogger().info("注册事件...");
        getProxy().getPluginManager().registerListener(plugin, new Listeners());

        getLogger().info("读取等级配置...");
        Base.maxLevel = level.getInt("level.max");
        Base.useOriginalLevel = level.getBoolean("level.upgrade.useOriginal");
        for (int i = 1; i <= level.getInt("level.upgrade.scope"); i++) {
            Base.scopeMap.put(i, level.getIntegerList("level.upgrade.function.scope" + i + ".scope"));
            Base.expMap.put(i, level.getInt("level.upgrade.function.scope" + i + ".exp"));
        }
        
        getLogger().info("注册命令...");
        getProxy().getPluginManager().registerCommand(this, new Commands());

        corresponder = new Corresponder(config.getString("correspond.host"), config.getInt("correspond.port"), 0);
        runTaskAsynchronously(new Runnable(){
			@Override
			public void run() {
                corresponder.start();
			}
        });
        getLogger().info("插件启动完成！"); 
    }

    @Override
    public void onDisable() {
        //保存数据
        if (Base.playerMap.size() == 0) {
            return;
        }
        for (Player player : Base.playerMap.values()) {
            try {
                mysql.savePlayer(player);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    private boolean isDatabaseNotConfigured() {
        return config.getString("mysql.host").isEmpty() 
            || config.getInt("mysql.port") == 0;
    }

    public static ScheduledTask runTaskAsynchronously(Runnable runnable) {
        return plugin.getProxy().getScheduler().runAsync(plugin, runnable);
    }

    public static ScheduledTask runTaskTimerAsynchronously(Runnable runnable, int second) {
        return plugin.getProxy().getScheduler().schedule(plugin, runnable, second, TimeUnit.SECONDS);
    }
}
